import global from '../global'
import React from "react";
import reqwest from "reqwest";
import autosize from 'autosize';
import Clipboard from 'clipboard'

import {Input, Form, Button, Table, Checkbox} from "antd";
const createForm = Form.create;
const FormItem = Form.Item;

const defaultPageSize = 10000;

const columns = [{
    title: '中文名',
    dataIndex: 'chineseName',
    width: '35%',
}, {
    title: '化妆品禁用组分',
    dataIndex: 'cosmeticForbidden',
    width: '10%',
}, {
    title: '禁用动（植）物组分',
    dataIndex: 'forbiddenBiota',
    width: '10%',
}];

let Demo = React.createClass({
    componentDidMount() {
        const {text, duplicateOperation} = this.state;
        this.props.form.setFieldsValue({
            text,
            duplicateOperation,
        });
        // resize
        autosize(document.querySelector('textarea'));
        var clipboardCN = new Clipboard('.handleCNCp', {
            text: () => {
                const {data}= this.state;
                return data.reduce((x, y) => {
                        return x + y.chineseName + "\n";
                    },
                    "");
            }
        });
        var clipboardENG = new Clipboard('.handleENGCp', {
            text: () => {
                const {data}= this.state;
                return data.reduce((x, y) => {
                        return x + y.englishName + "\n";
                    },
                    "");
            }
        });
        var clipboardTick = new Clipboard('.handleTickCp', {
            text: () => {
                const {data}= this.state;
                return data.reduce((x, y) => {
                        return x + y.cosmeticForbidden + "\t" + y.forbiddenBiota + "\n";
                    },
                    "");
            }
        });
    },

    handleReset(e) {
        e.preventDefault();
        this.props.form.resetFields();
        // resize to be changed
        autosize.update(document.querySelector('textarea'));
    },

    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            console.log('Submit!!!');
            console.log(values);
            this.setState(values);
            this.fetch(values);
        });
    },

    getInitialState() {
        return {
            data: [],
            pagination: {
                defaultPageSize: defaultPageSize,
            },
            loading: false,
            text: "",
            duplicateOperation: false
        };
    },

    handleTableChange(pagination, filters, sorter) {
        const pager = this.state.pagination;
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        const {text, duplicateOperation} = this.state;
        this.fetch({
            text: text,
            duplicateOperation: duplicateOperation,
            results: pagination.pageSize,
            page: pagination.current,
            sortField: sorter.field,
            sortOrder: sorter.order,
            ...filters,
        });
    },

    handleCNCp() {

    },

    handleENGCp() {

    },

    handleTickCp() {

    },

    fetch(params = {}) {
        console.log('params:', JSON.stringify(params));
        this.setState({loading: true});
        reqwest({
            url: global.apiServer + '/standard/chinese',
            method: 'get',
            data: {
                results: defaultPageSize,
                ...params,
            },
            type: 'json',
        }).then((ret) => {
            if (ret.code != 0) {
                alert(ret.msg);
                return;
            }
            const data = ret.data;
            console.log('data:', JSON.stringify(data));
            const pagination = this.state.pagination;
            // Read total count from server
            pagination.total = data.length;
            // pagination.total = 200;
            this.setState({
                loading: false,
                data: data,
                pagination,
            });
        });
    },

    render() {
        const {getFieldDecorator} = this.props.form;
        const textProps = getFieldDecorator('text', {
            rules: [
                {
                    required: true,
                    type: 'string',
                    message: '输入中文名称哈',
                }
            ],
        });

        const formItemLayout = {
            labelCol: {span: 7,  offset: 7},
            wrapperCol: {span: 12,  offset: 7},
        };
        return (
            <div>
                <Form horizontal>

                    <FormItem
                        label="中文名称："
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 16 }}
                        help="" >
                        {textProps(
                            <Input type="textarea" placeholder="请输入中文名称"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}>
                        <label>
                            {getFieldDecorator('duplicateOperation',
                                {valuePropName: 'checked',}
                            )(
                                <Checkbox />
                            )}
                            去重 &nbsp;
                        </label>
                        &nbsp;&nbsp;&nbsp;
                        <Button type="primary" onClick={this.handleSubmit}>确定</Button>
                        &nbsp;&nbsp;&nbsp;
                        <Button type="ghost" onClick={this.handleReset}>重置</Button>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}>
                        &nbsp;&nbsp;&nbsp;
                        <Button type="primary" className="handleCNCp" onClick={this.handleCNCp}>复制中文</Button>
                        &nbsp;&nbsp;&nbsp;
                        {/*<Button type="primary" className="handleENGCp" onClick={this.handleENGCp}>复制英文</Button>*/}
                        &nbsp;&nbsp;&nbsp;
                        <Button type="primary" className="handleTickCp" onClick={this.handleTickCp}>复制对勾</Button>
                    </FormItem>

                </Form>

                <Table columns={columns}
                       rowKey={record => record.key}
                       dataSource={this.state.data}
                       pagination={this.state.pagination}
                       loading={this.state.loading}
                       onChange={this.handleTableChange}
                />

            </div>

        );
    },
});

export default Demo = createForm()(Demo);